package concurrency.basicthreading.demo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 线程的优先级是将改线程的重要程度传递给线程调度器。线程调度器倾向于让线程优先级高的线程先执行。
 * 优先级低的线程仅仅是执行的频率较低(也就是说，线程优先级不会导致死锁)。
 * 
 * JDK 有10个优先级，但是多数系统不能映射的很好。。windows只有7个优先级。所以唯一可以用于移植的的方法是
 * 只使用 MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY
 */
public class Demo05Prioritys implements Runnable {
	private int countDown = 5;
	private int priority;
	private volatile double d;
	
	public Demo05Prioritys(int priority) {
		this.priority = priority;
	}

	public double getD() {
		return d;
	}

	public void setD(double d) {
		this.d = d;
	}

	public String toString() {
		return "[ThreadID:" + Thread.currentThread().getId() + 
					"]          [Thread Priority:" +  Thread.currentThread().getPriority() + 
					"]          [countDown:" + countDown + "]";
	}
	
	@Override
	public void run() {
		//最好不要再构造函数中设置线程的优先级。因为Executor此时还没有执行任务。
		Thread.currentThread().setPriority(priority);
		while (true) {
			for(int i = 0; i < 100000; i++) {
				setD(getD() + (Math.PI + Math.E) / (double)i);
				if (i % 1000 == 0)	Thread.yield();
			}
			System.out.println(this);
			
			if (--countDown == 0) return;
		}
	}

	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		
		for (int i = 0; i < 5; i++) {
			exec.execute(new Demo05Prioritys(Thread.MIN_PRIORITY));
		}
		exec.execute(new Demo05Prioritys(Thread.MAX_PRIORITY));
		
		exec.shutdown();
	}
}
